package com.example.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.example.vo.ResultVoEnum;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JSONAuthentication {
    /**
     * 输出JSON
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    public static void WriteJSON(HttpServletRequest request,
                             HttpServletResponse response,
                             ResultVoEnum resultVoEnum) throws IOException, ServletException {
        //这里很重要，否则页面获取不到正常的JSON数据集
        response.setContentType("application/json;charset=UTF-8");
        //跨域设置
        response.setHeader("Access-Control-Allow-Method", "*");
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.addHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.addHeader("Access-Control-Max-Age", "120");


        //输出JSON
        PrintWriter out = response.getWriter();
        SerializeConfig config = new SerializeConfig();
        config.configEnumAsJavaBean(ResultVoEnum.class);
        out.write(JSON.toJSONString(resultVoEnum,config));
        out.flush();
        out.close();
    }
}
